package com.csmy.my.center.action;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.attilax.html.HtmlX;
import com.attilax.io.filex;
import com.attilax.lang.text.RowParser;
import com.csmy.my.center.module.UserInfo;
import com.csmy.my.center.service.GoodInfoService;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.FileUtils;
import com.csmy.my.center.util.PageModel;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.dataconvert.impl.BaseDto;
//import com.sun.org.apache.bcel.internal.generic.NEW;

import common.Logger;

/**
 * 商品管理action
 * 
 * @author wgp
 * @see 2013-08-15
 * 
 */
@Controller
@Scope("prototype")
public class GoodInfoAction extends BaseActionSupport {

	private static final long serialVersionUID = -7494234699032976084L;
	// 日志记录
	Logger log = Logger.getLogger(GoodInfoAction.class);

	FileUtils fileUtils = new FileUtils();
	public PageModel pager = new PageModel();

	@Autowired
	private GoodInfoService goodInfoService;

	public static final String FOOD_TYPE_INDEX = "good_type_index";// 分类初始页面
	public static final String FOOD_TYPE_TREE = "good_type_tree";// 分类树结构
	public static final String FOOD_TYPE_LIST = "good_type_list";// 分类列表
	public static final String FOOD_TYPE_ADD = "good_type_add";// 分类增加
	public static final String FOOD_TYPE_EDIT = "good_type_edit";// 分类修改
	public static final String FOOD_TYPE_SEE = "good_type_see";// 分类查看

	public static final String FOOD_INFO_INDEX = "good_info_index";// 商品初始页面
	public static final String FOOD_INFO_TREE = "good_info_tree";// 商品树结构
	public static final String FOOD_INFO_LIST = "good_info_list";// 商品列表
	public static final String FOOD_INFO_ADD = "good_info_add";// 商品增加
	public static final String FOOD_INFO_EDIT = "good_info_edit";// 商品修改
	public static final String FOOD_INFO_SEE = "good_info_see";// 商品查看

	// 商品套餐
	public static final String SKU_INFO_LIST = "sku_info_list";// 商品套餐列表
	public static final String SKU_INFO_ADD = "sku_info_add";// 商品套餐增加
	public static final String SKU_INFO_EDIT = "sku_info_edit";// 商品套餐修改
	
	// 商品文案
	public static final String GOOD_COPY_LIST = "good_copy_list";// 商品文案列表
	public static final String GOOD_COPY_ADD = "good_copy_add";// 商品文案增加
	public static final String GOOD_COPY_EDIT = "good_copy_edit";// 商品文案修改

	public static final String ERROR = "error";// 错误页面

	HttpServletRequest request = ServletActionContext.getRequest();
	HttpServletResponse response = ServletActionContext.getResponse();
	HttpSession session = request.getSession();

	/**
	 * 商品分类初始页面
	 * 
	 * @return
	 */
	public String goodTypeInit() {
		try {
			// 跳到主页面
			return FOOD_TYPE_INDEX;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	/**
	 * 商品管理初始页面
	 * 
	 * @return
	 */
	public String goodInfoInit() {
		try {
			// 跳到主页面

			return FOOD_INFO_INDEX;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	/**
	 * 获取商品分类树结构
	 * 
	 * @return
	 */
	public String getGoodTypeTree() {
		try {

			Dto pDto = new BaseDto();
			UserInfo userInfo = getUser(request);

			String listerTreeData = "";
			String linkUrl = "good!getGoodTypeInfo.ct?flag=1";
			List<Dto> dList = CTReader.queryForList("good.getGoodTypeInfo");
			if (CTUtils.isNotEmpty(dList)) {
				listerTreeData = getCommZTreeJsonData(dList, "type_id",
						"type_name", "parent_id", linkUrl, "foodTypeTable",
						"分类管理",true, request);
			}
			request.setAttribute("foodTypeTreeData", listerTreeData);

			return FOOD_TYPE_TREE;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	/**
	 * 获取商品分类树结构
	 * 
	 * @return
	 */
	public String getGoodTree() {
		try {

			Dto pDto = new BaseDto();
			UserInfo userInfo = getUser(request);

			String listerTreeData = "";
			String linkUrl = "good!getGoodInfo.ct?flag=1";
			List<Dto> dList = dList = CTReader.queryForList("good.getGoodTypeInfo");
			if (CTUtils.isNotEmpty(dList)) {
				listerTreeData = getCommZTreeJsonData(dList, "type_id",
						"type_name", "parent_id", linkUrl, "foodTable", "分类管理",true,
						request);
			}
			request.setAttribute("foodTypeTreeData", listerTreeData);

			return FOOD_INFO_TREE;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	/**
	 * 获取商品分类列表数据
	 * 
	 * @return
	 */
	public String getGoodTypeInfo() {
		List<Dto> dList = null;
		try {
			// 获取所有参数信息
			Dto dto = getPraramsAsDto(request);
			// 处理中文
			String page_query = dto.getAsString("pageQuery");
			String queryParam = dto.getAsString("searchText");
			dto.put("queryParam", queryParam);

			dto = getPageDto(dto);
			dList = CTReader.queryForPage("good.getGoodTypeInfo", dto);
			Integer totalCount = (Integer) CTReader.queryForObject("good.getGoodTypeInfoCount", dto);
			pager = getPageModel(dList, dto.getAsInteger("start"), totalCount);

			// 返回参数到页面
			request.setAttribute("pm", pager);
			request.setAttribute("alisaname", queryParam);

			return FOOD_TYPE_LIST;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	/**
	 * 获取商品分类列表数据
	 * 
	 * @return
	 */
	public String getGoodSkuInfo() {
		List<Dto> dList = null;
		try {
			// 获取所有参数信息
			Dto dto = getPraramsAsDto(request);
			// 处理中文
			String page_query = dto.getAsString("pageQuery");
			String queryParam = dto.getAsString("searchText");
			dto.put("queryParam", queryParam);

			dto = getPageDto(dto);
			dList = CTReader.queryForPage("good.getGoodSkuInfo", dto);

			Integer totalCount = (Integer) CTReader.queryForObject(
					"good.getGoodSkuInfoCount", dto);
			pager = getPageModel(dList, dto.getAsInteger("start"), totalCount);

			// 返回参数到页面
			request.setAttribute("pm", pager);
			request.setAttribute("alisaname", queryParam);

			return SKU_INFO_LIST;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	// 增加套餐
	public String addFoodSku() {
		return SKU_INFO_ADD;
	}

	// 修改套餐
	public String editFoodSku() {
		Dto dto = getPraramsAsDto(request);
		String good_id = dto.getAsString("good_id");

		return SKU_INFO_EDIT;
	}

	/**
	 * 获取商品列表数据
	 * 
	 * @return
	 */
	public String getGoodInfo() {
		List<Dto> dList = null;
		try {
			// 获取所有参数信息
			Dto dto = getPraramsAsDto(request);
			// 处理中文
			String page_query = dto.getAsString("pageQuery");
			String queryParam = dto.getAsString("searchText");
			dto.put("queryParam", queryParam);

			dto = getPageDto(dto);
			dList = CTReader.queryForPage("good.getGoodInfo", dto);
			Integer totalCount = (Integer) CTReader.queryForObject(
					"good.getGoodInfoCount", dto);
			pager = getPageModel(dList, dto.getAsInteger("start"), totalCount);

			// 返回参数到页面
			request.setAttribute("pm", pager);
			request.setAttribute("alisaname", queryParam);

			return FOOD_INFO_LIST;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	/**
	 * 获取商品文案列表数据
	 * 
	 * @return
	 */
	public String getGoodCopyList() {
		List<Dto> dList = null;
		try {
			// 获取所有参数信息
			Dto dto = getPraramsAsDto(request);
			// 处理中文
			String page_query = dto.getAsString("pageQuery");
			String queryParam = dto.getAsString("searchText");
			dto.put("queryParam", queryParam);

			dto = getPageDto(dto);
			dList = CTReader.queryForPage("good.getGoodCopyInfo", dto);
			Integer totalCount = (Integer) CTReader.queryForObject(
					"good.getGoodCopyInfoCount", dto);
			pager = getPageModel(dList, dto.getAsInteger("start"), totalCount);

			// 返回参数到页面
			request.setAttribute("pm", pager);
			request.setAttribute("alisaname", queryParam);

			return GOOD_COPY_LIST;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	/**
	 * 增加商品文案
	 * 
	 * @return
	 */
	public String addGoodCopy() {
		// 获取下拉数据
		Dto dto = getPraramsAsDto(request);
		List<Dto> dList = CTReader.queryForList("good.getGoodInfo", dto);
		request.setAttribute("goodList", dList);
		// 获取商户信息
		dto.put("enabled", "1");
		List<Dto> cList = CTReader.queryForList("resource.getCustomerInfo", dto);
		request.setAttribute("customerList", cList);
		
		request.setAttribute("optype", "add_copy");
		request.setAttribute("type_id", dto.getAsString("type_id"));
		return GOOD_COPY_ADD;
	}

	/**
	 * 修改商品文案
	 * 
	 * @return
	 */
	public String editGoodCopy() {
		// 获取下拉数据
		Dto dto = getPraramsAsDto(request);
		List<Dto> dList = CTReader.queryForList("good.getGoodInfo", dto);
		request.setAttribute("goodList", dList);
		// 获取商户信息
		dto.put("enabled", "1");
		List<Dto> cList = CTReader.queryForList("resource.getCustomerInfo", dto);
		request.setAttribute("customerList", cList);
		
		request.setAttribute("optype", "edit_copy");
		request.setAttribute("type_id", dto.getAsString("type_id"));
		Dto copyDto = (BaseDto)CTReader.queryForObject("good.getGoodCopyInfo", dto);
        request.setAttribute("goodCopyInfo", copyDto);
		return GOOD_COPY_EDIT;
	}

	/**
	 * 增加商品
	 * 
	 * @return
	 */
	public String addGoodInfo() {
		// 获取下拉数据
		Dto dto = getPraramsAsDto(request);
		List<Dto> tList = CTReader.queryForList("good.getGoodTypeInfo");
		request.setAttribute("typeList", tList);
		// 获取商户信息
		dto.put("enabled", "1");
		List<Dto> dList = CTReader.queryForList("resource.getCustomerInfo", dto);
		request.setAttribute("customerList", dList);
		// 获取商品标签
		List<Dto> foodtaglist = getCodeList("GOOD_TAG");
		request.setAttribute("foodtaglist", foodtaglist);
		
		//获取商品文案信息
		List<Dto> wxCopyList = CTReader.queryForList("good.getWXCopyInfo");
		List<Dto> spcCopyList = CTReader.queryForList("good.getSPCCopyInfo");
		List<Dto> zoneCopyList = CTReader.queryForList("good.getZoneCopyInfo");
		if(!StringUtil.checkListBlank(wxCopyList)){
			request.setAttribute("wxCopyList", wxCopyList);
		}else{
			request.setAttribute("wxCopyList", new ArrayList<Dto>());
		}
		
		if(!StringUtil.checkListBlank(spcCopyList)){
			request.setAttribute("spcCopyList", spcCopyList);
		}else{
			request.setAttribute("spcCopyList", new ArrayList<Dto>());
		}
		
		if(!StringUtil.checkListBlank(zoneCopyList)){
			request.setAttribute("zoneCopyList", zoneCopyList);
		}else{
			request.setAttribute("zoneCopyList", new ArrayList<Dto>());
		}
		
		Dto goodInfo = new BaseDto();
		request.setAttribute("goodInfo", goodInfo);
		request.setAttribute("optype", "add_good");

		return FOOD_INFO_ADD;
	}


	/**
	 * 修改商品
	 * 
	 * @return
	 */
	public String editGoodInfo() {
		// 获取下拉数据
		Dto dto = getPraramsAsDto(request);
		// 获取分类数据
		List<Dto> tList = CTReader.queryForList("good.getGoodTypeInfo");
		request.setAttribute("typeList", tList);
		// 获取商户数据
		dto.put("enabled", "1");
		List<Dto> dList = CTReader.queryForList("resource.getCustomerInfo", dto);
		request.setAttribute("customerList", dList);
		// 获取商品标签
		List<Dto> foodtaglist = getCodeList("GOOD_TAG");
		request.setAttribute("foodtaglist", foodtaglist);
		request.setAttribute("optype", "edit_good");

		// 通过编号获取实物信息
		Dto goodInfo = (BaseDto) CTReader.queryForObject("good.getGoodInfo",dto);
		if (CTUtils.isNotEmpty(goodInfo)) {
			
			List<Dto> skuList = CTReader.queryForList("good.getGoodSkuInfo", dto);
			if(!StringUtil.checkListBlank(skuList)){
				int cont = 0;
				StringBuffer sBuffer = new StringBuffer("");
				for (Dto skuDto : skuList) {
					cont++;
					String sku_id =  skuDto.getAsString("sku_id");
					String sku_name = skuDto.getAsString("sku_name");
					String sku_cost = skuDto.getAsString("sku_cost");
					String sku_price = skuDto.getAsString("sku_price");
					String sku_pmoney = skuDto.getAsString("sku_pmoney");
					String service_money = skuDto.getAsString("service_money");
					
					sBuffer.append("<tr>");
					sBuffer.append("<td><input id=\"sku" + cont
							+ "\" name=\"sku" + cont
							+ "\" type=\"text\" class=\"textinput2\" value=\""
							+ sku_name + "\" />");
					sBuffer.append("<input id=\"sku_id_" + cont
							+ "\" name=\"sku_id_" + cont
							+ "\" type=\"hidden\" value=\""
							+ sku_id + "\" /></td>");
					
					sBuffer.append("<td><input id=\"cb" + cont
							+ "\" name=\"cb" + cont
							+ "\" type=\"text\" class=\"textinput\" value=\""
							+ sku_cost + "\" /></td>");
					sBuffer.append("<td><input id=\"jg" + cont
							+ "\" name=\"jg" + cont
							+ "\" type=\"text\" class=\"textinput\" value=\""
							+ sku_price + "\" /></td>");
					sBuffer.append("<td><input id=\"fc" + cont
							+ "\" name=\"fc" + cont
							+ "\" type=\"text\" class=\"textinput\" value=\""
							+ sku_pmoney + "\" /></td>");
					sBuffer.append("<td><input id=\"kffc" + cont
							+ "\" name=\"kffc" + cont
							+ "\" type=\"text\" class=\"textinput\" value=\""
							+ service_money + "\" /></td>");
					sBuffer.append("</tr>");
					}
					request.setAttribute("good_sku", sBuffer.toString());
				}
			}
			
		//获取商品文案信息
		List<Dto> wxCopyList = CTReader.queryForList("good.getWXCopyInfo");
		List<Dto> spcCopyList = CTReader.queryForList("good.getSPCCopyInfo");
		List<Dto> zoneCopyList = CTReader.queryForList("good.getZoneCopyInfo");
		if(!StringUtil.checkListBlank(wxCopyList)){
			request.setAttribute("wxCopyList", wxCopyList);
		}else{
			request.setAttribute("wxCopyList", new ArrayList<Dto>());
		}
		
		if(!StringUtil.checkListBlank(spcCopyList)){
			request.setAttribute("spcCopyList", spcCopyList);
		}else{
			request.setAttribute("spcCopyList", new ArrayList<Dto>());
		}
		
		if(!StringUtil.checkListBlank(zoneCopyList)){
			request.setAttribute("zoneCopyList", zoneCopyList);
		}else{
			request.setAttribute("zoneCopyList", new ArrayList<Dto>());
		}

		request.setAttribute("goodInfo", goodInfo);
		return FOOD_INFO_ADD;
	}

	public void deleteGood() {
		String err_msg = "false";
		boolean temp = false;
		try {
			// 获取下拉数据
			Dto dto = getPraramsAsDto(request);
			StringUtil.xprint("param==" + dto);

			Dto fooDto = null;
			Dto inDto = new BaseDto();
			String fids[] = null;
			String big_file = "";
			String small_file = "";
			String video_file = "";
			String food_id = dto.getAsString("good_id");
			String containPath = StringUtil.getContainPath();
			String realPath = containPath + request.getContextPath() + "/";
			StringUtil.xprint("realPath==" + realPath);

			// 删除文件
			fids = food_id.split(",");
			for (int i = 0; i < fids.length; i++) {
				inDto.put("good_id", fids[i]);
				fooDto = (BaseDto) CTReader.queryForObject("good.getGoodInfo",inDto);
				if (CTUtils.isNotEmpty(fooDto)) {
					big_file = fooDto.getAsString("good_pic");
					if (CTUtils.isNotEmpty(big_file)) {
						big_file = big_file.replace('\\', '/');
						StringUtil.xprint("pic_file=" + realPath + big_file);
						if (fileUtils.delFile(realPath + big_file)) {
							StringUtil.xprint("删除商品【" + fids[i] + "】图片成功...");
						} else {
							StringUtil.xprint("删除商品【" + fids[i] + "】图片失败...");
						}
					}
				}
			}

			temp = goodInfoService.operGoodInfo(dto);
			if (temp) {
				err_msg = "true";
			} else {
				err_msg = "false";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.renderText(err_msg);
		}
	}

	/**
	 * 增加商品分类
	 * 
	 * @return
	 */
	public String addGoodTypeInfo() {
		// 获取当前参数
		Dto dto = getPraramsAsDto(request);
		List<Dto> dList = CTReader.queryForList("good.getGoodTypeInfo");
		request.setAttribute("typeList", dList);
		return FOOD_TYPE_ADD;
	}
	
	/**
	 * 修改商品分类
	 * 
	 * @return
	 */
	public String editGoodTypeInfo() {
		// 获取当前参数
		Dto dto = getPraramsAsDto(request);
		List<Dto> dList = CTReader.queryForList("good.getGoodTypeInfo");
		request.setAttribute("typeList", dList);

		Dto foodTypeInfo = (Dto) CTReader.queryForObject("good.getGoodTypeByID", dto);
		request.setAttribute("foodTypeInfo", foodTypeInfo);

		return FOOD_TYPE_EDIT;
	}

	/**
	 * 查看商品分类
	 * 
	 * @return
	 */
	public String seeGoodTypeInfo() {
		// 获取当前参数
		Dto dto = getPraramsAsDto(request);
		request.setAttribute("cardTypeJsonData", getCombJsonData("CARDTYPE"));
		request.setAttribute("enabledJsonData", getCombJsonData("STATE"));
		request.setAttribute("lockedJsonData", getCombJsonData("STATE"));

		Dto cardInfo = (Dto) CTReader.queryForObject("resource.getVipCardById",dto);
		request.setAttribute("cardInfo", cardInfo);
		return FOOD_TYPE_SEE;
	}

	/**
	 * 操作用户信息呢
	 */
	public void operGoodInfo() {
		boolean temp = false;
		String err_msg = "false";
		try {
			Dto dto = getPraramsAsDto(request);
			if (CTUtils.isNotEmpty(dto)) {
				temp = goodInfoService.operGoodInfo(dto);
				if (temp) {
					err_msg = "true";
				} else {
					err_msg = "false";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			renderText(err_msg);
		}
	}
	
	
	
	@SuppressWarnings("unchecked")
	public void saveGood() throws UnsupportedEncodingException {
		Dto dto = getPraramAsDto(request);
		dto.put("copy_title", dto.getAsString("copy_title"));
		String content = dto.getAsString("copy_content");
		content = CTUtils.rhtml(content);
		dto.put("copy_content",content);
		if(CTUtils.isEmpty(dto.getAsString("type_id"))){
			dto.put("type_id", "0");
		}
		
		
		//ati 
		if( StringUtils.isEmpty(dto.getAsString("copy_id")))
			dto.put("copy_id", filex.getUUidName());
		
		String txt= HtmlX.html2txtV2( dto.get("copy_content").toString());
		Map part = new RowParser().parse(txt);
		dto.put("salalei", part.get("薪资水平"));
		dto.put("sala_mode", part.get("结算模式"));
		dto.put("worktime", part.get("工作时间"));
		dto.put("location", part.get("工作地点"));
		
		
		
	 
		boolean temp = goodInfoService.operGoodInfo(dto);
		if(temp){
		   this.renderHtml("<script>alert('数据保存成功！');window.location.href='good!getGoodCopyList.ct';</script>");
		}else{
		   this.renderHtml("<script>alert('数据保存失败！');window.location.href='good!getGoodCopyList.ct';</script>");
		}
	}

	public PageModel getPager() {
		return pager;
	}

	public void setPager(PageModel pager) {
		this.pager = pager;
	}

	public GoodInfoService getGoodInfoService() {
		return goodInfoService;
	}
	
	public void setGoodInfoService(GoodInfoService goodInfoService) {
		this.goodInfoService = goodInfoService;
	}

}
